package com.example.mqmanager.config;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

@Component
public class DynamicRedisConfig {
    
    // 存储不同Redis连接的工厂
    private final Map<String, RedisConnectionFactory> connectionFactoryMap = new ConcurrentHashMap<>();
    
    private String host = "localhost";
    private int port = 6379;
    private String password = "";
    private int database = 0;

    public RedisConnectionFactory getConnectionFactory() {
        return getConnectionFactory(host, port, password, database);
    }
    
    public RedisConnectionFactory getConnectionFactory(String host, int port, String password, int database) {
        String key = host + ":" + port + ":" + database;
        return connectionFactoryMap.computeIfAbsent(key, k -> {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(host);
            config.setPort(port);
            config.setDatabase(database);
            if (password != null && !password.isEmpty()) {
                config.setPassword(password);
            }
            LettuceConnectionFactory factory = new LettuceConnectionFactory(config);
            factory.afterPropertiesSet(); // 确保连接工厂正确初始化
            return factory;
        });
    }

    // Getters and Setters
    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getDatabase() {
        return database;
    }

    public void setDatabase(int database) {
        this.database = database;
    }
}